<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\Bill;
use App\Logic\BillLogic;
use Excel;
use Illuminate\Support\Facades\DB;

class BillController extends BaseController
{
		
	public function __construct()
	{
		
	}
    
 
	/*
	 * 代理商账单明细
	 * return array
	 */
	public function agent(Request $request,$id){
		$where[] = ['del_flag','=',0];
		//账单明细列表
		if ($request->input('start')&&$request->input('end')){
			$where[]=['operate_time', '>=', $request->start." 00:00:00"];
			$where[]=['operate_time', '<=', $request->end." 23:59:59"];
		}
		$bills = BillLogic::getBillList($where);
		
		if(!$id){
			$this->export($bills);
		}
		
		return $this->view('agent',compact('bills','id'));
	}
	
	/*
	 * 财务公司账单明细
	 * return array
	 */
    public function finance(Request $request,$id){
    	$where[] = ['del_flag','=',0];
    	//账单明细列表
    	if ($request->input('start')&&$request->input('end')){
//            $where[] =[DB::raw(
//                "DATE_FORMAT(operate_time,'%Y/%m/%d') between '".
//                $request->input('start'))
//                ,'and',$request->input('end')];
            $where[]=['operate_time', '>=', str_replace('/','-',$request->input('start'))." 00:00:00"];
            $where[]=['operate_time', '<=', str_replace('/','-',$request->input('end'))." 23:59:59"];
        }
        $bills = BillLogic::getBillList($where);  
  
    	if(!$id){
    		$this->export($bills);
    	}

    	return $this->view(null,compact('bills','id'));
    }

    public function export(){  	
    	$where[] = ['del_flag','=',0];
    	$list = BillLogic::getBillExportData($where);
    	ini_set('memory_limit','500M');
    	set_time_limit(0);
    	$cellData[] = array('类别','时间','金豆','来源');
    	foreach($list as $val){
    		$cellData[] = [$val['consume_category'],$val['operate_time'],$val['consume_amount'],$val['operate_description']];
    	}
    	//dd($cellData);
    	Excel::create('账单信息',function($excel) use ($cellData){
    		$excel->sheet('bill', function($sheet) use ($cellData){
    			$tot = count($cellData);
    			$sheet->setWidth(array(
    				'A'=>12,'B'=>20,'C'=>12,'D'=>12  					
    			));
    					
     			$sheet->rows($cellData);
    			$sheet->cells('A1:A'.$tot, function($cells) {
    				$cells->setAlignment('left');
    			});
    			$sheet->cells('A1:C'.$tot, function($cells) {
    			    $cells->setAlignment('left');
    			});

    		});
    	})->export('xls');
    	die;
    } 
     
}
